import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:ecy_app_flutter/routes/blind_box/blind_box_list.dart';
import 'package:ecy_app_flutter/routes/blind_box/category_image_selector.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/EcyExchangeMarketPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxDetail extends StatefulWidget {
  const BlindBoxDetail({super.key,required this.commodityPageList});
  final List<BlindBoxDetailMore> commodityPageList;

  @override
  State<BlindBoxDetail> createState() => _BlindBoxDetailState();
}

class _BlindBoxDetailState extends State<BlindBoxDetail> {
  _BlindBoxDetailState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);

  int _currentPage = 1;
  bool _hasMore = false;
  List<bool> isSelected = List.filled(13, false);

  final List<int> indexList = List.filled(19, 0);
  final List<CommodityTop> _commodityTopList = [];

  // 新增：模拟图片和已购买数据
  final List<String> imgList = [
    'https://picsum.photos/400/600?image=10',
    'https://picsum.photos/400/600?image=20',
    'https://picsum.photos/400/600?image=30',
    'https://picsum.photos/400/600?image=40',
    'https://picsum.photos/400/600?image=50',
    'https://picsum.photos/400/600?image=10',
    'https://picsum.photos/400/600?image=20',
    'https://picsum.photos/400/600?image=30',
    'https://picsum.photos/400/600?image=40',
    'https://picsum.photos/400/600?image=50',
  ];
  List<bool> isBought = [false, true, false, false, true,false, true, false, false, true]; // 注意：不再final，便于刷新
  int currentIndex = 0;
  final PageController _pageController = PageController();

  // 弹窗相关状态
  bool showResultDialog = false;
  String resultTitle = "恭喜你抽中";
  String resultName = "五条悟";
  String resultImg = "https://picsum.photos/200/200?image=10";

  @override
  void initState() {
    super.initState();
    _refreshData("");
    fetchBoughtStatus(); // 页面加载时获取已购买状态
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "pageIndex": _currentPage,
        "pageSize": 2,
        "search": search,
      };
      var response = await EcyRequestbasemanager().get("/app/api/app/top/top", body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<BlindBoxDetailMore> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => BlindBoxDetailMore.fromJson(json));
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var commodityPageList = commonPage.records ?? [];
          if (_currentPage == 1) {
            widget.commodityPageList.clear();
          }
          setState(() {
            widget.commodityPageList.addAll(commodityPageList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  // 1. 购买图片接口调用
  Future<void> buyImage(int imageIndex) async {
    // TODO: 替换为真实接口
    // var response = await EcyRequestbasemanager().post(
    //   "/api/buyImage",
    //   {"imageIndex": imageIndex, "userId": "yourUserId"},
    // );
    // if (response['code'] == 200) {
    //   setState(() { isBought[imageIndex] = true; });
    //   ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('购买成功！')));
    // } else {
    //   ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('购买失败，请重试')));
    // }
    // --- 本地模拟 ---
    await Future.delayed(Duration(milliseconds: 500));
    setState(() {
      isBought[imageIndex] = true;
    });
    // ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('购买成功！')));
  }

  // 2. 页面加载时获取已购买状态
  Future<void> fetchBoughtStatus() async {
    // TODO: 替换为真实接口
    // var response = await EcyRequestbasemanager().get(
    //   "/api/getBoughtStatus",
    //   {},
    // );
    // if (response['code'] == 200) {
    //   List<int> boughtIndexes = List<int>.from(response['data']);
    //   setState(() {
    //     for (int i = 0; i < isBought.length; i++) {
    //       isBought[i] = boughtIndexes.contains(i);
    //     }
    //   });
    // }
    // --- 本地模拟 ---
    await Future.delayed(Duration(milliseconds: 500));
    // 假设后端返回图片1和图片4已被买
    List<int> boughtIndexes = [1,4,7,8,9];
    setState(() {
      for (int i = 0; i < isBought.length; i++) {
        isBought[i] = boughtIndexes.contains(i);
      }
    });
  }

  // 切换到下一个可用图片
  void goToNextImage() {
    int next = currentIndex;
    do {
      next = (next + 1) % imgList.length;
    } while (isBought[next] && next != currentIndex);
    setState(() {
      currentIndex = next;
      _pageController.jumpToPage(currentIndex);
    });
  }

  // 切换到上一个可用图片
  void goToPreviousImage() {
    int prev = currentIndex;
    do {
      prev = (prev - 1 + imgList.length) % imgList.length;
    } while (isBought[prev] && prev != currentIndex);
    setState(() {
      currentIndex = prev;
      _pageController.jumpToPage(currentIndex);
    });
  }

  Widget _buildGoodsGrid() {
    int itemsPerRow = 3;
    int rowCount = (imgList.length / itemsPerRow).ceil();
    List<Widget> rows = [];
    for (int row = 0; row < rowCount; row++) {
      int start = row * itemsPerRow;
      int end = (start + itemsPerRow > imgList.length) ? imgList.length : start + itemsPerRow;
      rows.add(
        Padding(
          padding: EdgeInsets.only(bottom: 8.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List.generate(end - start, (i) {
              int index = start + i;
              bool bought = isBought[index];
              bool selected = isSelected[index];
              return GestureDetector(
                onTap: bought
                    ? null
                    : () {
                        setState(() {
                          isSelected[index] = !isSelected[index];
                          currentIndex = index;
                        });
                      },
                child: Container(
                  margin: EdgeInsets.all(2),
                  width: 104.w,
                  height: 128.h,
                  decoration: BoxDecoration(
                    color: bought
                        ? Colors.grey[200]
                        : (selected ? Colors.pinkAccent.withOpacity(0.2) : Colors.white),
                    border: Border.all(
                      color: bought
                          ? Colors.grey[300]! // 已买用灰色
                          : (selected ? Colors.pink : Colors.grey[300]!),
                      width: bought
                          ? 1 // 已买用细边
                          : (selected ? 2 : 1),
                    ),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Stack(
                    children: [
                      Center(
                        child: bought
                            ? Icon(Icons.block, color: Colors.grey, size: 20)
                            : ClipRRect(
                                borderRadius: BorderRadius.circular(8.r),
                                child: Image.network(imgList[index], fit: BoxFit.cover, width: 104.w, height: 128.h),
                              ),
                      ),
                      if (!bought && selected)
                        const Positioned(
                          right: 2,
                          top: 2,
                          child: Icon(Icons.check_circle, color: Colors.pink, size: 16),
                        ),
                    ],
                  ),
                ),
              );
            }),
          ),
        ),
      );
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: rows,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          backgroundColor: const Color(0XFFF5F5F5),
          appBar: AppBar(
            title: Text('盲抽选择', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w700, color: Color(0xFF000000)),),
            centerTitle: true,
            backgroundColor: const Color(0XFFF5F5F5),
            leadingWidth: 50.w,
            scrolledUnderElevation: 0,
            leading: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                EcyRouter.pop(context, "");
              },
              child: Align(
                alignment: Alignment.centerRight,
                child: Image.asset(
                  "assets/images/ic_back.png",
                  width: 30.w,
                ),
              ),
            ),
            actions: [
              GestureDetector(
                  onTap: () {},
                  child: Padding(
                    padding: EdgeInsets.only(right: 12.w),
                    child: Image.asset(
                      'assets/images/kf.png',
                      width: 24.w,
                      height: 24.h,
                    ),
                  )),
              GestureDetector(
                  onTap: () {},
                  child: Padding(
                      padding: EdgeInsets.only(right: 16.w),
                      child: Image.asset(
                        'assets/images/share.png',
                        width: 24.w,
                        height: 24.h,
                      )))
            ],
          ),
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                  "assets/images/blind_box_bg@2x.png",
                ),
                fit: BoxFit.cover,
              ),
            ),
            child: Stack(
              children: [
                // 主内容
                Column(
                  children: [
                    // SizedBox(height: 16.h),
                    // 位置指示器占位（避免被内容遮挡）
                    SizedBox(height: 8),
                    CategoryImageSelector(commodityList: widget.commodityPageList),
                    // SizedBox(height: 8),
                    Padding(
                      padding: EdgeInsets.fromLTRB(16.w, 0, 0, 0), 
                      child: Align(
                              alignment: Alignment.centerLeft, 
                              // child: _buildPositionIndicator()
                            )
                    ),
                    Expanded(
                      child: SingleChildScrollView(
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          child: _buildGoodsGrid(),
                        ),
                      ),
                    ),
                    _buildButton(),
                    SizedBox(height: 20.h), // 底部间距
                  ],
                ),
              ],
            ),
          ),
          bottomNavigationBar: GestureDetector(
            onTap: () {
              showModalBottomSheet(
                context: context,
                isScrollControlled: true, // 允许全屏
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                ),
                builder: (context) => Container(
                  height: MediaQuery.of(context).size.height * 0.8,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                  ),
                  child: Center(child: EcyExchangeMarketPage()),
                ),
              );
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20),
              ),
              height: 82.h,
              child: Column(
                
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Icon(CupertinoIcons.chevron_compact_up),
                  SizedBox(height: 10.h),
                  const Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Text('互换集市'),
                      // Text('我的交换'),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
        // 全屏弹窗
        if (showResultDialog)
          Positioned.fill(
            child: Container(
              color: Colors.black.withOpacity(0.6),
              child: Center(
                child: Container(
                  width: 300.w,
                  padding: EdgeInsets.symmetric(vertical: 32.h, horizontal: 16.w),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    borderRadius: BorderRadius.circular(24.r),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(resultTitle, style: TextStyle(fontSize: 18.sp, color: Colors.white, fontWeight: FontWeight.bold)),
                      SizedBox(height: 8.h),
                      Text(resultName, style: TextStyle(fontSize: 22.sp, color: Colors.white, fontWeight: FontWeight.w700)),
                      SizedBox(height: 16.h),
                      ClipOval(
                        child: Image.network(resultImg, width: 120.w, height: 120.w, fit: BoxFit.cover),
                      ),
                      SizedBox(height: 16.h),
                      Text("已收入盲盒\n可在'我的盲盒'中与他人互换", textAlign: TextAlign.center, style: TextStyle(fontSize: 14.sp, color: Colors.white)),
                      SizedBox(height: 24.h),
                      SizedBox(
                        width: double.infinity,
                        height: 44.h,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Color(0xFFEA4B9B),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22.r)),
                          ),
                          onPressed: () {
                            setState(() {
                              showResultDialog = false;
                            });
                          },
                          child: Text("拆下一个", style: TextStyle(fontSize: 16.sp, color: Colors.white)),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
      ],
    );
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 70.w, height: 70.h, fit: BoxFit.cover);

 

  
  Widget _buildButton() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        width: 140.w,
        height: 40.h,
        decoration: BoxDecoration(
          gradient: LinearGradient(colors: [Colors.white, Colors.white]),
          borderRadius: BorderRadius.circular(24),
        ),
        child: TextButton(
          onPressed: isBought[currentIndex]
              ? null
              : () async {
                  await buyImage(currentIndex);
                  setState(() {
                    showResultDialog = true;
                    resultName = "五条悟"; // 可根据实际抽中内容赋值
                    resultImg = imgList[currentIndex];
                  });
                },
          style: TextButton.styleFrom(
            padding: EdgeInsets.zero,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          ),
          child: Text(
            '全部拆开',
            style: TextStyle(
              fontFamily: "PingFang SC",
              fontWeight: FontWeight.w700,
              fontSize: 16.sp,
              color: const Color(0xFFEA4B9B),
            ),
          ),
        ),
      ),
    );
  }


  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    super.dispose();
  }
}
